﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CommonLib.Pattern.FSM;
public class EnemyFSMStatePatrol : EnemyFSMStateBase
{
	public EnemyFSMStatePatrol(RoleCtrl _role, IFSM fsm = null) : base("Patrol", _role, fsm)
	{
		this.Role = _role;
	}


	protected override void OnEnter()
	{
		base.OnEnter();
		TransitionParam tp = GetTransistionParam(TransitionParamType.Prtrol);
		//vigilance = tp.VigilancePatrol;
		vigilance = 1920;
		//Reset To TiredTime
		startTime = Time.fixedTime;
	}

	protected override void OnExit()
	{
		base.OnExit();
		//Role = null;
	}

	protected override void OnUpdate()
	{
		base.OnUpdate();

		if (Time.fixedTime - startTime >= triedTime)
			target = null;
		Collider2D forwardTarget = null;
		if (FindNearestForward(vigilance, out Collider2D col))
		{
			forwardTarget = col;
		}

		/*
		int mulSearch = 1;
		while(null == forwardTarget)
		{
			if (FindNearestForward(mulSearch * vigilance, out Collider2D col))
			{
				forwardTarget = col;
			}
			else
			{
				mulSearch++;
			}
		}*/
		if (null != forwardTarget)
		{
			Vector2 steering = new Vector2(forwardTarget.transform.position.x - Role.transform.position.x,
				forwardTarget.transform.position.y - Role.transform.position.y).normalized;

			Vector2 desired = (Role.SubManagerMove.VelocityDir + steering).normalized;
			//role.SubManagerMove.Rb2d.velocity = desired.normalized * role.RoleEntity.CurrentSpeed;
			Role.SubManagerMove.SetVelocityDir(desired);
		//	Debug.Log("EPChainNodeItemForward");
		}
		else
		{
		//	Debug.Log("EPChainNodeItemForward Not");
		}
	}

	public Collider2D TiredTarget => target;
	protected float startTime = 0;
	protected float triedTime = 3;
}
